﻿using log4net;
using Mangox.Common;
using Mangox.Model.Common;
using Mangox.Model.MyBusinessDB;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Mangox.BLL.Stock
{
    public class StockPoolBLL
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";

        /// <summary>
        /// 分页获取股票池列表
        /// 也可以使用id，cede，name等获取
        /// </summary>
        /// <returns></returns>
        public PageResult<StockPool> GetStockPoolList(StockPoolReq param)
        {
            PageResult<StockPool> page = new PageResult<StockPool>();
            page.Data = new List<StockPool>();
            page.ResultType = ResultType.Success;
            List<StockPool> list = null;

            try
            {
                using (MyBusinessDBContext db = new MyBusinessDBContext())
                {
                    //EF条件拼接/取数据库模型
                    var obj = db.StockPools.Where(t => true);


                    //缓存有数据取缓存
                    var listCache = (List<StockPool>)CacheHelper.GetCache("poolList");
                    if (listCache != null && listCache.Count > 0)
                    {
                        //List转IQueryable 用于查询
                        obj = listCache.AsQueryable();
                    }
                    

                    if (param.ID > 0)
                    {
                        obj = obj.Where(t => t.ID == param.ID);
                    }

                    //*查询关键字，%like开头StartsWith，结尾EndsWith
                    //*Contains有空会异常，这里处理
                    if (!string.IsNullOrEmpty(param.KeyWord))
                    {
                        //清除无用的字符
                        param.KeyWord = param.KeyWord.Replace(" ", "").Replace("'", "").Replace(",", "").Replace("，", "").Replace(";", "");

                        //包含"关键字"的全部取出来Contains，排序再根据"关键字"开头StartsWith
                        if (OtherHelper.IsNumber(param.KeyWord))
                        {
                            obj = obj.Where(t => (string.IsNullOrWhiteSpace(t.StockCode) ? false : t.StockCode.Contains(param.KeyWord)))
                                .OrderByDescending(t => (string.IsNullOrWhiteSpace(t.StockCode) ? false : t.StockCode.StartsWith(param.KeyWord)));
                        }
                        else if (OtherHelper.IsEnglish(param.KeyWord))
                        {
                            param.KeyWord = param.KeyWord.ToUpper();
                            //使用全拼
                            /*
                            if (param.KeyWord.Length > 4)
                            {
                                obj = obj.Where(t => (string.IsNullOrWhiteSpace(t.PinYinFull) ? false : t.PinYinFull.Contains(param.KeyWord)))
                                  .OrderByDescending(t => (string.IsNullOrWhiteSpace(t.PinYinFull) ? false : t.PinYinFull.StartsWith(param.KeyWord)));
                            }
                            else
                            {
                                //缓存区分大小写(这里转成大写)/数据库sql不区分
                                obj = obj.Where(t => t.PinYin.Contains(param.KeyWord)).OrderByDescending(t => t.PinYin.StartsWith(param.KeyWord));
                            }*/

                            //全拼/简拼混合搜索
                            obj = obj.Where(t => (string.IsNullOrWhiteSpace(t.PinYin) ? false : t.PinYin.Contains(param.KeyWord)) 
                            || (string.IsNullOrWhiteSpace(t.PinYinFull) ? false : t.PinYinFull.Contains(param.KeyWord)))
                                .OrderByDescending(t => (string.IsNullOrWhiteSpace(t.PinYin) ? false : t.PinYin.StartsWith(param.KeyWord)))
                                .ThenByDescending(t => (string.IsNullOrWhiteSpace(t.PinYinFull) ? false : t.PinYinFull.StartsWith(param.KeyWord)));
                        }
                        else
                        {
                            obj = obj.Where(t => (string.IsNullOrWhiteSpace(t.StockName) ? false : t.StockName.Contains(param.KeyWord)))
                                .OrderByDescending(t => (string.IsNullOrWhiteSpace(t.StockName) ? false : t.StockName.StartsWith(param.KeyWord)));
                        }
                    }

                    //空数据不查询 t.StockCode != "" 不能是text类型
                    obj = obj.Where(t => t.StockCode != "");

                    //注意代码有前缀
                    if (!string.IsNullOrEmpty(param.StockCode))
                    {
                        obj = obj.Where(t => t.StockCode == param.StockCode);
                    }

                    if (!string.IsNullOrEmpty(param.StockName))
                    {
                        obj = obj.Where(t => t.StockName == param.StockName);
                    }

                    if (!string.IsNullOrEmpty(param.State) && OtherHelper.IsNumber(param.State))
                    {
                        obj = obj.Where(t => t.State == Convert.ToInt32(param.State));
                    }

                    //上海，深圳
                    //if (param.BazaarType > 0)
                    //{
                    //    obj = obj.Where(t => t.BazaarType == (int)param.BazaarType);
                    //}

                    if (!string.IsNullOrEmpty(param.AffiIndustry))
                    {
                        obj = obj.Where(t => t.AffiIndustry == param.AffiIndustry);
                    }

                    //Count这里暂时不需要返回
                    //page.Count = obj.Count();
                    //不是关键字搜索使用，Skip需要排序才支持
                    if (string.IsNullOrEmpty(param.KeyWord))
                    {
                        //EF分页
                        obj = obj.OrderByDescending(t => t.StockCode);
                        obj = obj.Skip((param.Index - 1) * param.PageSize).Take(param.PageSize);
                    }
                    else
                    {
                        obj = obj.Skip((param.Index - 1) * param.PageSize).Take(param.PageSize);
                    }

                    list = obj.ToList();
                    page.PageIndex = param.Index;
                    page.Data = list;

                    //if (list != null && list.Count > 0)
                    //{
                    //    foreach (var item in list)
                    //    {
                    //        page.Data.Add(item);
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "GetStockPoolList fail-{0}", ex);
                page.ResultType = ResultType.LogicError;
                page.Message = ex.Message;
            }
            return page;
        }

        /// <summary>
        /// 获取所有股票池，用于缓存
        /// </summary>
        /// <returns></returns>
        public List<StockPool> GetStockPoolList()
        {
            List<StockPool> list = null;
            try
            {
                using (MyBusinessDBContext dbContext = new MyBusinessDBContext())
                {
                    list = dbContext.StockPools.Where(t => t.State == 1).ToList();
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "GetStockPoolList() fail-{0}", ex);
            }
            return list;
        }




        #region 用户搜索股票记录

        /// <summary>
        /// 添加股票搜索记录
        /// 添加示例
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool AddStockSearch(StockSearch param)
        {
            try
            {
                if (param == null)
                {
                    return false;
                }
                using (MyBusinessDBContext db = new MyBusinessDBContext())
                {
                    param.CreateTime = DateTime.Now;

                    db.StockSearches.Add(param);
                    var f = db.SaveChanges() > 0;
                    return f;
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(className + "AddUserActive fail-{0}", ex);
            }
            return false;
        }


        #endregion



    }
}
